<template>
  <div class="app-container">
    <div class="div-style" style="height: 420px;">
      <el-row v-if="trDisabled" :gutter="10" style="margin-bottom: -25px;">
        <el-col :span="1.5">
          <el-button plain type="primary" @click="handleAdd">
            <template #icon>
              <i-ep-plus/>
            </template>
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button :disabled="multiple" plain type="danger" @click="handleDelete">
            <template #icon>
              <i-ep-delete/>
            </template>
            删除
          </el-button>
        </el-col>
      </el-row>
      <template-master ref="templateMasterRef" :query-params="queryParams" @row-click="rowClick"
                       @handle-update="handleUpdate"/>

      <!-- 添加或修改模板主记录对话框 -->
      <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body draggable
                 width="500px">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="权限" prop="authorityType">
            <el-select v-model="form.authorityType">
              <el-option v-for="dict in dictDataMap[
                                'template_authority_type'
                            ]" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="模板名称" prop="title">
            <el-input v-model="form.title" placeholder="请输入模板名称" @input="titleInput"/>
          </el-form-item>
          <el-form-item label="适用科室" prop="deptId">
            <base-dept-tree :org-id="form.orgId" :value="form.deptId" style="width: 100%;"
                            @deptSelect="deptSelect"/>
          </el-form-item>
          <el-form-item label="处方类型" prop="itemClass">
            <el-radio-group v-model="form.itemClass">
              <el-radio v-for="(dict, index) in dictDataMap['bill_item_class_dict']"
                        v-show="dict.dictValue === 'A' || dict.dictValue === 'B'" :key="dict.dictValue"
                        :value="dict.dictValue">{{
                  dict.dictLabel
                }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="发药药房" prop="storageId">
            <el-select v-model="form.storageId" placeholder="请输入发药药房">
              <el-option v-for="drugVsDept in drugVsDeptList" :key="drugVsDept.id"
                         :label="drugVsDept.storageName" :value="drugVsDept.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.startFlag">
              <el-radio v-for="dict in dictDataMap['sys_yes_no']" :key="dict.dictValue"
                        :value="dict.dictValue">{{
                  dict.dictLabel
                }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
                    <span class="dialog-footer">
                        <el-button type="primary" @click="submitForm">确 定</el-button>
                        <el-button @click="cancel">取 消</el-button>
                    </span>
        </template>
      </el-dialog>
    </div>
    <div class="div-style mt10" style="height: calc(100% - 430px)">
      <template-item ref="templateItemRef" :apply-item="applyItem" :detail-is-show="detailIsShow"
                     :is-show="true" :query-params="queryParams"/>
    </div>
  </div>
</template>

<script setup lang="ts">
import {addTemplateMaster, delTemplateMaster, updateTemplateMaster,} from "@/api/patient/templateMaster.ts";
import {getDrugVsDeptList} from "@/api/drug/drugStorageDept.ts"
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {firstLetterResult} from "@/utils/pinyin";
import templateMaster from "./templateMaster.vue"
import templateItem from "./templateItem.vue"

const {proxy} = getCurrentInstance() as any;
const props = defineProps({
  trDisabled: {
    type: Boolean,
    default: true
  }
})
const dictStore = useDictStoreHook();
const detailIsShow = ref("1")
let dictDataMap = ref(
  dictStore.isTypeGetData(
    "template_type",
    "sys_yes_no",
    "template_authority_type",
    "bill_item_class_dict"
  )
);
const adaptiveHeight = ref(props.trDisabled ? 560 : 200)
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const formRef = ref();
const templateItemRef = ref()
const templateMasterRef = ref([]);
const multiple = ref(true);
const open = ref(false);
const total = ref(0);
const title = ref("");
const ids = ref([]);
const applyItem = ref<TemplateMasterType>({})
// 药房list
const drugVsDeptList = ref<any>([])
const queryParams = ref<TemplateMasterType>({
  pageNum: 1,
  pageSize: 10,
  type: "1",
  authorityType: userInfo.customerType != '3' ? '' : "0",
  title: "",
  titleInput: "",
  deptId: userInfo.loginDeptId,
  orgId: userInfo.orgId,
});
const form = ref<TemplateMasterType>({
  type: "1",
  authorityType: "0",
  title: "",
  titleInput: "",
  deptId: "",
  deptName: "",
  storageId: "",
  startFlag: "Y",
  itemClass: "A",
  orgId: queryParams.value.orgId
});
const rules = {
  authorityType: [
    {
      required: true,
      message: "权限不能为空",
      trigger: "change",
    },
  ],
  title: [
    {
      required: true,
      message: "模板主题名称不能为空",
      trigger: "blur",
    },
  ],
  startFlag: [
    {
      required: true,
      message: "状态不能为空",
      trigger: "blur",
    },
  ],
  deptId: [
    {
      required: true,
      message: "科室不能为空",
      trigger: "blur",
    },
  ],
  storageId: [
    {
      required: true,
      message: "发药药房不能为空",
      trigger: "blur",
    },
  ],
};

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId
  // queryParams.value.authorityType = userInfo.customerType != '3' ? '' : "0"
  getList()
} else {
  queryParams.value.orgId = ""
}

// 以科室id查询对应的药房、药库信息
function getDrugVsDeptListFun() {
  let data = {
    deptId: form.value.deptId,
    orgId: userInfo.orgId,
    clinicOrVisitArray: proxy.$stringToArray("4,2,0", ","),
    storageTypeArray: proxy.$stringToArray("2,4", ","),
    drugGrantTypeArray: proxy.$stringToArray("1", ","),
  }
  getDrugVsDeptList(data).then((res: any) => {
    drugVsDeptList.value = res.data
  })
}

/** 查询模板主记录列表 */
function getList() {
  nextTick(() => {
    templateMasterRef.value.getList()
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择机构");
  }
  queryParams.value.pageNum = 1;
  getList();
}

/** 新增按钮操作 */
function handleAdd() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择机构");
  }
  open.value = true;
  reset();
  title.value = "添加模板主记录";
}

function handleUpdate(row: any) {
  open.value = true;
  reset();
  form.value = row
  getDrugVsDeptListFun()
  title.value = "修改模板主记录";
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      if (form.value.templateMasterId != "") {
        updateTemplateMaster(form.value)
          .then((response: any) => {
            ElMessage.success("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
          });
      } else {
        addTemplateMaster(form.value)
          .then((response: any) => {
            ElMessage.success("新增成功");
            open.value = false;
            getList();
          })
          .finally(() => {
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _templateMasterIds = row.templateMasterId || ids.value;
  ElMessageBox.confirm("是否确认删除模板数据项？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delTemplateMaster(_templateMasterIds).then(() => {
        getList();
        ElMessage.success("删除成功");
      });
    })
    .catch(() => {
    });
}

// 表单重置
function reset() {
  form.value = {
    templateMasterId: "",
    type: "1",
    authorityType: "0",
    title: "",
    titleInput: "",
    deptId: "",
    deptName: "",
    storageId: "",
    startFlag: "Y",
    orgId: queryParams.value.orgId,
    createBy: "",
    createTime: "",
    updateBy: "",
    updateTime: "",
    delFlag: "0",
    itemClass: "A"
  };
  nextTick(() => {
    formRef.value.resetFields();
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 科室点击事件
function deptSelect(node) {
  form.value.deptId = node.deptId
  form.value.deptName = node.deptName
  getDrugVsDeptListFun()
}

// 主题生成拼音码
function titleInput(value) {
  if (value) {
    form.value.titleInput = firstLetterResult(value)
  } else {
    form.value.titleInput = ""
  }
}

// 主表行点击事件
function rowClick(row: any) {
  applyItem.value = row
  detailIsShow.value = row.itemClass
  nextTick(() => {
    templateItemRef.value.rowClick(row)
  })
}

getList();
</script>

<script lang="ts">
export default {
  name: "PrescriptionTemplate"
}
</script>

<style scoped></style>
